# -*- coding: utf-8 -*-
import gmpy
'''
仿射解密.  解密，明文和key无关。加密，密文和key有关。
python2.7
'''
def affine_decrypt():
    key = '????????????????????????????????????'
    flag= 'flag{??????????????????????????????}'
     
    #data='6df47d03c4a79a3010503010507d20507d6d6d3020d750aa304d9ad77a507daa3da77df4f497e3f1'
    data='c82c49aea85d947a777d7a777d49f97d49c8c87af9e27d157ac594e2917d4915435d492c2cdcc374'
    encrypted = [int(data[i:i+2], 16) for i in range(0, len(data), 2)]
    plaindelta = ord(flag[1])- ord(flag [0])
    cipherdalte= encrypted[1]- encrypted[0]
    a = gmpy.invert(plaindelta,257) * cipherdalte % 257
    b = (encrypted[0] - a * ord(flag[0])) % 257
    a_inv = gmpy. invert(a, 257)
    result1=""
    result2=""
    for c in encrypted:
        m = (c-b) * a_inv % 257
        result1 += chr(m)
        result2 += '%02x' % m
    print('m = %s'%result1)
    print('m_hex = %s'%result2)
    #flag{this_is_an_affine_cipher_acutally!}

def affine_crypt():
    key  = '123456789012345678901234567890'
    flag = 'flag{this_is_an_affine_cipher_acutally!}'

    n = len(key) / 2
    encrypted = ''
    for c in flag:
        c = ord(c)
        for i in range(n):
            c = (ord(key[i]) * c + ord(key[i + n])) % 257
        encrypted += '%02x' % c
    print('encrypted: %s'%encrypted)
    
if __name__ == '__main__':
    affine_crypt()
    affine_decrypt()